#include "choosefrienddialog.h"
#include <QHBoxLayout>
#include <QPushButton>
#include <QScrollArea>
#include <QScrollBar>
#include <QStyleOption>
#include <QPainter>
#include "debug.h"
#include "model/data.h"
#include "model/datacenter.h"
#include "toast.h"
ChooseFriendItem::ChooseFriendItem(const QString& userId,const QIcon& avatar,const QString& name,bool isChecked,ChooseFriendDialog* owner)
    :owner(owner),userId(userId)
{
    //1.设置属性和布局管理器
    this->setFixedHeight(50);
    QHBoxLayout* layout = new QHBoxLayout(this);
    layout->setAlignment(Qt::AlignLeft);
    //2.添加控件
    checkBox = new QCheckBox;
    checkBox->setChecked(isChecked);

    avatarBtn = new QPushButton;
    avatarBtn->setIcon(avatar);
    avatarBtn->setFixedSize(40,40);
    avatarBtn->setIconSize(QSize(40,40));
    avatarBtn->setStyleSheet("QPushButton{border:none;}");

    nameLabel = new QLabel;
    QFont font("微软雅黑",10,30);
    nameLabel->setFont(font);
    nameLabel->setText(name);

    layout->addWidget(checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);
    //3.初始化信号和槽
    connect(checkBox,&QCheckBox::toggled,this,[=](bool isChecked)
    {
        if(isChecked)
            owner->checkedFriendItem(this);
        else
        {
            ChooseFriendItem* leftItem=nullptr;
            ChooseFriendItem* rightItem = nullptr;
            for(int i =0;i<owner->leftContainer->layout()->count();i++)
            {
                auto item = owner->leftContainer->layout()->itemAt(i);
                if(item&&item->widget())
                {
                    ChooseFriendItem* CFItem = dynamic_cast<ChooseFriendItem*>(item->widget());
                    if(CFItem->userId==userId)
                    {
                        leftItem = CFItem;
                        break;
                    }
                }
            }
            for(int i =0;i<owner->rightContainer->layout()->count();i++)
            {
                auto item = owner->rightContainer->layout()->itemAt(i);
                if(item&&item->widget())
                {
                    ChooseFriendItem* CFItem = dynamic_cast<ChooseFriendItem*>(item->widget());
                    if(CFItem->userId==userId)
                    {
                        rightItem = CFItem;
                        break;
                    }
                }
            }
            if(leftItem==nullptr||rightItem==nullptr)
                return;
            owner->uncheckedFriendItem(leftItem,rightItem);
        }
    });

}


void ChooseFriendItem::paintEvent(QPaintEvent* event)
{
    (void) event;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
void ChooseFriendItem::enterEvent(QEnterEvent* event)
{
    this->setStyleSheet("QWidget{background-color:rgb(230,230,230);}");
}
void ChooseFriendItem::leaveEvent(QEvent* event)
{
    this->setStyleSheet("QWidget{background-color:white;}");
}
QCheckBox* ChooseFriendItem::getCheckBox()
{
    return checkBox;
}

ChooseFriendItem* ChooseFriendItem::copyItem(ChooseFriendItem* item)
{

    ChooseFriendItem* ret= new ChooseFriendItem(item->userId,item->avatarBtn->icon(),item->nameLabel->text(),
                                                 item->checkBox->isChecked(),item->owner);
    return ret;
}

ChooseFriendDialog::ChooseFriendDialog(QWidget* parent,const QString& sessionOwnerId)
    :QDialog(parent),sessionOwnerId(sessionOwnerId)
{
    //1.设置属性
    this->setWindowTitle("选择好友");
    this->setFixedSize(750,550);
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setStyleSheet("QWidget{background-color:white;}");

    //2.设置布局管理器
    QHBoxLayout* layout = new QHBoxLayout(this);

    //3.初始化左右边
    initLeft();
    initRight();

}
void ChooseFriendDialog::initLeft()
{
    //1.添加可滑动窗口到左边
    QScrollArea* scrollArea = new QScrollArea;
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal{height:0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical{width:3px;background-color:rgb(216,216,216);}");
    dynamic_cast<QHBoxLayout*>(this->layout())->addWidget(scrollArea,1);
    leftContainer = new QWidget;
    scrollArea->setWidget(leftContainer);

    //2.在这个滑动窗口上设置布局管理器，并添加控件
    QVBoxLayout* layout = new QVBoxLayout(leftContainer);
    layout->setAlignment(Qt::AlignTop);

#if TEST_UI
    //测试数据
    for(int i =0;i<30;i++)
    {
        ChooseFriendItem* friendItem = new ChooseFriendItem("666"+QString::number(i),QIcon(":/myResource/Image/dogAvatar.svg"),"dog"+QString::number(i),false,this);
        layout->addWidget(friendItem);
    }
#endif
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    QList<model::UserInfo>* friendList = dataCenter->getFriendList();
    for(int i =0;i<friendList->size();i++)
    {
        const model::UserInfo f =(*friendList)[i];
        if(f.userId==dataCenter->getMyself()->userId||f.userId==sessionOwnerId)
            continue;
        ChooseFriendItem* friendItem = new ChooseFriendItem(f.userId,f.avatar,f.nickname,false,this);
        layout->addWidget(friendItem);
    }
}
void ChooseFriendDialog::initRight()
{
    //1.在右侧添加布局管理器
    QGridLayout* layout = new QGridLayout;
    dynamic_cast<QHBoxLayout*>(this->layout())->addLayout(layout,1);
    layout->setContentsMargins(10,10,10,10);
    layout->setSpacing(10);


    //2.在布局管理器中添加控件
    QLabel* tag = new QLabel;
    QFont font("微软雅黑",12,90);
    tag->setFont(font);
    tag->setText("选择联系人");
    layout->addWidget(tag,0,0,1,2);

    QScrollArea* scrollArea = new QScrollArea;
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal{height:0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical{width:3px;background-color:rgb(216,216,216);}");
    rightContainer = new QWidget;
    scrollArea->setWidget(rightContainer);
    QVBoxLayout* vlayout = new QVBoxLayout(rightContainer);
    vlayout->setAlignment(Qt::AlignTop);
    layout->addWidget(scrollArea,1,0,1,2);

    QString style ="QPushButton{border:1px solid black;border-radius:5px;background-color:white;}";
    style+="QPushButton:pressed{background-color:rgb(210,210,210);}";
    QPushButton* okBtn = new QPushButton;
    okBtn->setText("确定");
    okBtn->setFixedSize(100,40);
    okBtn->setStyleSheet(style);
    QPushButton* cancelBtn = new QPushButton;
    cancelBtn->setText("取消");
    cancelBtn->setFixedSize(100,40);
    cancelBtn->setStyleSheet(style);

    layout->addWidget(okBtn,2,0,1,1,Qt::AlignHCenter);
    layout->addWidget(cancelBtn,2,1,1,1,Qt::AlignHCenter);
    connect(okBtn,&QPushButton::clicked,this,&ChooseFriendDialog::clickCreateSessionBtn);
    connect(cancelBtn,&QPushButton::clicked,this,[this](){this->close();});
}
void ChooseFriendDialog::addFriendItem(ChooseFriendItem* item)
{
    bool isChecked = item->getCheckBox()->isChecked();
    leftContainer->layout()->addWidget(item);
    if(isChecked)
    {
        ChooseFriendItem* item2 = ChooseFriendItem::copyItem(item);
        rightContainer->layout()->addWidget(item2);
    }
}
void ChooseFriendDialog::checkedFriendItem(ChooseFriendItem* item)
{
    ChooseFriendItem* item2 = ChooseFriendItem::copyItem(item);
    rightContainer->layout()->addWidget(item2);
}
void ChooseFriendDialog::uncheckedFriendItem(ChooseFriendItem* leftItem,ChooseFriendItem* rightItem)
{
    leftItem->getCheckBox()->setChecked(false);
    rightContainer->layout()->removeWidget(rightItem);
    rightItem->deleteLater();
}

void ChooseFriendDialog::clickCreateSessionBtn()
{
    model::DataCenter* dataCenter =model::DataCenter::getInstance();
    QList<QString> *memberIdList = getCreateSessionMemberList();
    LOG()<<"创建群聊的人数为:"<<memberIdList->size();
    if(memberIdList->size()<3)
    {
        Toast::showMessage("群聊人数不足3人，无法创建");
        return;
    }

    dataCenter->createSessionAsync(*memberIdList);
    delete memberIdList;
    this->close();
}

QList<QString>* ChooseFriendDialog::getCreateSessionMemberList()
{
    model::DataCenter* dataCenter =model::DataCenter::getInstance();
    QList<QString>* memberIdList = new QList<QString>;
    //发起创建群聊的人和这个单聊会话的拥有者一定是在这个新的群聊中的
    memberIdList->push_back(dataCenter->getMyself()->userId);
    memberIdList->push_back(sessionOwnerId);
    auto layout = rightContainer->layout();

    for(int i =0;i<layout->count();i++)
    {
        auto* item = (layout->itemAt(i));
        if(!item||!item->widget()) continue;
        memberIdList->push_back(dynamic_cast<ChooseFriendItem*>(item->widget())->getUserId());
    }
    return memberIdList;
}




